package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.domain.CourseChapter;
import cn.itsource.ymcc.query.CourseChapterQuery;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.service.ICourseChapterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/courseChapter")
public class CourseChapterController {

    @Autowired
    public ICourseChapterService courseChapterService;

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody CourseChapter courseChapter){
        if(courseChapter.getId()!=null){
            courseChapterService.updateById(courseChapter);
        }else{
            //service层要重写save方法，目的是设置章节的排序number
            courseChapterService.save(courseChapter);
        }
        return JsonResult.me();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        courseChapterService.removeById(id);
        return JsonResult.me();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.me().setData(courseChapterService.getById(id));
    }

    /**
    * 根据课程id查询该课程的章节   章节必须与视频组装成树形结构
    */
    @GetMapping("/loadTreeByCourseId/{courseId}")
    public JsonResult loadTreeByCourseId(@PathVariable("courseId")Long courseId){
        return JsonResult.me().setData(courseChapterService.loadTreeByCourseId(courseId));
    }

    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.me().setData(courseChapterService.list(null));
    }
    /**
    * 根据课程id查询该课程下所有章节
    */
    @GetMapping("/listByCourseId/{courseId}")
    public JsonResult listByCourseId(@PathVariable("courseId")Long courseId){
        return JsonResult.me().setData(courseChapterService.list(new QueryWrapper<CourseChapter>()
            .eq("course_id", courseId)
            .orderByAsc("number")));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody CourseChapterQuery query){
        Page<CourseChapter> page = new Page<CourseChapter>(query.getPageNo(), query.getPageSize());
        page = courseChapterService.page(page);
        return JsonResult.me().setData(new PageList<CourseChapter>(page.getTotal(), page.getRecords()));
    }
}
